<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="请选择所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="请选择所属组织" :props="props" :options="organOptions" @change="selectOrgan" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.type" clearable placeholder="请选择类型">
              <el-option v-for="item in query.typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item>
            <el-button v-has="'ROLE_LIST'" type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'ROLE_EDIT'" type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="角色名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="角色代码" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="110" align="center" prop="type" :formatter="typeFormater" />
        <el-table-column label="所属组织" width="110" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.organName }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-link v-has="'ROLE_EDIT'" icon="el-icon-edit" style="cursor: pointer;" type="warning" @click="handleEdit(scope.$index, scope.row)">
              修改
            </el-link>
            <el-link v-has="'ROLE_REMOVE'" class="el-icon-delete" type="danger" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-link v-has="'ROLE_AUTH_BATCH_MODIFY'" class="el-icon-milk-tea" type="primary" style="cursor: pointer;" @click="handleAssignAuth(scope.$index,scope.row)">
              赋权
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="角色编号">
            <el-input v-model="form.id" disabled placeholder="角色编号" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="角色名称">
            <el-input v-model="form.name" auto-complete="off" />
          </el-form-item>
          <el-form-item label="角色代码">
            <el-input v-model="form.code" auto-complete="off" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="form.type" placeholder="类型" style="width:100%">
              <el-option v-for="item in query.typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogAssignOrganFormVisible">
        <el-form :inline="true" :model="role" style="width:100%">
          <el-form-item v-if="false">
            <el-input v-model="role.id" placeholder="角色名称" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
        </el-form>
        <el-card class="box-card">
          <el-tree ref="tree" :data="authorityList" :default-expand-all="false" :props="defaultProps" :check-strictly="false" show-checkbox node-key="id" highlight-current />
        </el-card>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAssignOrganFormVisible = false">取 消</el-button>
          <el-button v-has="'ROLE_AUTH_MODIFY_ROLE_AUTHS'" type="primary" @click="handleAssginAuthorities">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getList, doDelete, doEdit, modifyRoleAuth, getAssignedPagination } from '@/api/role'
import { getBelong2RoleAndOthers, getOrganOriginAndRoleHasAuthorities } from '@/api/authority'
import { querySubordinateOrgan } from '@/api/Organ'
import { getDictionaryGroup } from '@/api/dictionary'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSuperManagerId, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const typeMap = {
        '1': '超级管理员',
        '2': '管理员',
        '3': '普通用户'
      }
      const typeDesc = typeMap[status]
      return typeDesc
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      dialogAssignOrganFormVisible: false,
      addForVisible: false,
      role: {
        id: ''
      },
      organ: {
        id: ''
      },
      form: {
        name: '管理员',
        code: 'ROLE_MGR',
        type: '1',
        organId: '',
        organPath: ''
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增角色',
        edit: '编辑角色',
        assign: '分配权限'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      valueId: {}, // 初始ID（可选）
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      title: '组织',
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      query: {
        params: {
          name: '', // 角色名称
          organId: null,
          organPath: null
        },
        authority:{
          name: '',
          operationType: '',
          platformType: '',
          parentId: '',
          organId: '',
          organPath: '',
          path: '',
          code: '',
          type: '',
          roleId: '',
          url: '',
          id: ''
        },
        timeValue: '',
        typeOptions: [{
          value: '1',
          label: '超级管理员'
        }, {
          value: '2',
          label: '普通管理员'
        }, {
          value: '3',
          label: '用户'
        }],
        value: ''
      },
      authlistLoading: false,
      multipleSelection: [],
      authorityList: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        url: 'url'
      },
      defaultSelectedNodes: []
    }
  },
  created() {
    let that = this
    this.initOrganTree(() => {
      that.setOrganQueryType()
    }, getOrganPath())
    this.handleFiltTenant()
    this.initOrganFormTree()
    this.handleBuildRoleTypeOptions()
    this.fetchData()
  },
  methods: {
    typeFormater(row, column) {
      let label = ''
      for (let i = 0; i < this.query.typeOptions.length; i++) {
        if ('' + row.type === this.query.typeOptions[i].value) {
          return this.query.typeOptions[i].label
        }

      }
      return label
    },
    fetchData() {
      debugger
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getAssignedPagination(this.query.params,
        this.currentPage,
        this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    initOrganTree(fn, filter, that) {
      debugger
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      if (this.props.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {}, nodesInfo[0].data.organPath, that)
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    fetchAuthorityList(params) {
      this.authlistLoading = true
      this.query.authority.tenantId = params.tenantId || getTenantId()
      this.query.authority.organId = params.organId || getOrganId()
      this.query.authority.roleId = params.id 
      debugger
      this.query.authority.organPath = params.organPath || getOrganPath() 
      getOrganOriginAndRoleHasAuthorities(this.query.authority).then(response => {
        const data = response.data
        if (data.successful) {
          const selectedNodes = getSelectedNodesObject(data.data, 'hasAuthority')
          this.authorityList = handleBuildTreeDataStruct(data.data, 'id', 'parentId')
          this.authlistLoading = false
          this.listLoading = false
          this.defaultSelectedNodes = selectedNodes
          this.$nextTick(function() {
            this.handleDefaultSelected(selectedNodes)
          })
        }else{
          this.$message.error(getSystemErrorCode(data.status))
        }
      })
    },
    handleDefaultSelected(selectedNodes) {
      for (let i = 0; i < selectedNodes.length; i++) {
        this.$refs.tree.setChecked(selectedNodes[i], true, false)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.fetchData()

    },
    // 新增
    handleAdd() {
      let that = this
      this.initOrganFormTree(function() {
        // 显示弹框
        that.dialogFormVisible = true
      })
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.id = ''
      this.form.name = ''
      this.form.code = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      let that = this
      this.initOrganFormTree(function() {
        // 显示弹框
        that.dialogFormVisible = true
      })
      this.form.id = row.id
      this.form.name = row.name
      this.form.code = row.code
      this.form.type = '' + row.type
      this.form.tenantId = row.tenantId
      this.form.organId = row.organId
      this.form.organPath = row.organPath
      this.addForVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {
      this.form.organId = this.form.organId || getOrganId()
      this.form.organPath = this.form.organPath || getOrganPath()
      this.form.createBy = getCurrentLoginUserId()
      this.form.updateBy = getCurrentLoginUserId()
      doEdit(this.form).then(response => {
        console.log(response)
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleAssignAuth(index, row) {
      this.dialogAssignOrganFormVisible = true
      this.form.tenantId = row.tenantId
      this.form.organId = row.organId
      this.dialogStatus = 'assign'
      this.listLoading = true
      this.fetchAuthorityList(row)
      this.role.id = row.id
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },

    getSelectedNodes(dataList) {
      const selectedNodes = []
      const selectedKeys = {}
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].hasAuth) {
          selectedNodes.push(dataList[i].idStringValue)
          selectedKeys[dataList[i].id] = true
        }
      }
      sessionStorage.setItem('smr-blade-session-ROLEAUTHS',
        JSON.stringify(selectedKeys))

      return selectedNodes
    },
    handleAssginAuthorities() {
      const checkedList = this.$refs.tree.getCheckedNodes()
      const halfCheckList = this.$refs.tree.getHalfCheckedNodes()
      const batchModify = []

      const allChecked = []

      for (let i = 0; i < checkedList.length; i++) {
        allChecked.push(checkedList[i])
      }

      debugger
      for (let i = 0; i < halfCheckList.length; i++) {
        allChecked.push(halfCheckList[i])
      }

      for (let i = 0; i < allChecked.length; i++) {
        const roleAuth = {}
        roleAuth['id'] = allChecked[i].roleAuthId
        roleAuth['roleId'] = this.role.id
        roleAuth['authId'] = allChecked[i].id
        if (this.form.organId) {
          roleAuth['organId'] = this.form.organId
        } else {
          roleAuth['organId'] = getOrganId()

        }
        if (this.form.tenantId) {
          roleAuth['tenantId'] = this.form.tenantId
        } else {
          roleAuth['tenantId'] = getTenantId()
        }
        batchModify.push(roleAuth)
      }

      modifyRoleAuth(batchModify, this.role.id, this.form.organId).then(response => {
        console.log(response)
        const data = response.data
        if (!data) {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        } else if (data.status >= 1) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.dialogAssignOrganFormVisible = false
        } else if (data.status === 403) {
          this.$message({
            type: 'warning',
            message: data.description
          })
        }
      })
    },
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys())
    },
    setCheckedNodes(nodes) {
      this.$refs.tree.setCheckedNodes(nodes)
    },
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3])
    },
    handleBuildRoleTypeOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserRole" && item.parentId != '0';
      })
      let typeOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        typeOptions.push(option)
      }
      this.query.typeOptions = typeOptions
    }

  }
}

</script>
